package com.msg2phone.sync;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

import com.msg2phone.util.Constant;
import com.msg2phone.util.NetType;
import com.msg2phone.util.NetworkUtil;
import com.msg2phone.util.SimpleUrlApp;

public class MainActivity extends Activity {
	WebView webView;
	private Handler handler = null;
	private static final String JAVASCRIPT = "javascript:";
	private static final String BRC = "()";
	private static final String BRC_OPEN = "('";
	private static final String BRC_CLOSE = "')";
	private static final String FLASK_DOMAIN = "www.msg2phone.dotcloud.com";
	private static final String SELECTS_RESOURCE = "/selection/all";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//判断当前网络是否可用
		if (NetworkUtil.getNetworkState(getApplicationContext())){
			Toast.makeText(this, "Connected Successfully!", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, "Connected Failed!", Toast.LENGTH_LONG).show();
		}
		sendCellLac();
		
		webView = new WebView(this);
		setContentView(webView);
		handler = new Handler();
		// mWebView.setWebViewClient(new NewsClient());
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setDomStorageEnabled(true);
		webView.addJavascriptInterface(this, "selectSupport");
		loadPage("index.html");
	}

	public void loadPage(String in) {
		final String url = Constant.HTML_ROOT + in;
		loadURL(url);
	}

	private void loadURL(final String in) {
		handler.post(new Runnable() {
			public void run() {
				webView.loadUrl(in);
			}
		});
	}

	public void getAllSelects(String callback, String accountCallback) {
		final String accountCallbackFunction = JAVASCRIPT + accountCallback
				+ BRC;

		Log.e("ddd", "getAllSelects");
		
		//获得网络类型
		NetType netType = NetworkUtil.getNetType(getApplicationContext());
		
		final String json = SimpleUrlApp.getUrlData(FLASK_DOMAIN,SELECTS_RESOURCE,netType);

		final String callbackFunction = JAVASCRIPT + callback + BRC_OPEN + json + BRC_CLOSE;
		Log.e("ddd", callbackFunction);
		// loadURL(callbackFunction);
		webView.loadUrl(callbackFunction);
	}

	public void showLog(String tag, String msg) {
		Log.e(tag, msg);
	}
	
	private void sendCellLac(){
		int cid = 0;
		int lac = 0;
		//TelephonyManager
		TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		String OperatorName = tm.getNetworkOperatorName();
		if(OperatorName != ""){
			try{
				GsmCellLocation location = (GsmCellLocation)tm.getCellLocation();
				cid = location.getCid();
				lac = location.getLac();
				int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
				int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
				
				//组装JSON查询字符串 
				JSONObject holder = new JSONObject(); 
				holder.put("version", "1.1.0"); 
				holder.put("host", "maps.google.com"); 
				// holder.put("address_language", "zh_CN"); 
				holder.put("request_address", true);
				
				JSONArray array = new JSONArray(); 
				JSONObject data = new JSONObject(); 
				data.put("cell_id", cid); // 25070 
				data.put("location_area_code", lac);// 4474 
				data.put("mobile_country_code", mcc);// 460 
				data.put("mobile_network_code", mnc);// 0 
				array.put(data); 
				holder.put("cell_towers", array);
				System.out.println(holder.toString());
				
//				//获得网络类型
//				NetType netType = NetworkUtil.getNetType(getApplicationContext());
//				
//				StringBuffer document = new StringBuffer();
//				URL urlget;
//				HttpURLConnection connection = null;
//					
//				if (netType != null && netType.isWap()) {
//					urlget =  new  URL("http://10.0.0.172:80/loc/json");
//					connection = (HttpURLConnection)urlget.openConnection();  
//				    connection.setRequestProperty("X-Online-Host","www.google.com");
//				    connection.setRequestProperty("Accept","*/*");
//				}
////					urlget = new URL(url);
////					HttpURLConnection connection = (HttpURLConnection) urlget.openConnection();
//				
//				connection.connect();
//				BufferedReader reader = new BufferedReader(new InputStreamReader(
//						connection.getInputStream()));
//				String line = null;
//				while ((line = reader.readLine()) != null)
//					document.append(line);
				
//				// 创建连接，发送请求并接受回应 
//				DefaultHttpClient client = new DefaultHttpClient();
//				HttpPost post = new HttpPost("http://www.google.com/loc/json");
//				
//				StringEntity se = new StringEntity(holder.toString());
//				post.setEntity(se); 
//				
//				HttpResponse resp = client.execute(post);
////				HttpEntity entity = resp.getEntity();
////				InputStream in = entity.getContent();
//				BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); 
//				StringBuffer sb = new StringBuffer();
//				String result = "";
//				while ((result = br.readLine()) != null) {
//					sb.append(result);
//				}
			}
			catch(Exception e){
				System.out.println(e.getMessage());
			}
		}
	}
}